import { patchZero, toast } from '@/utils/tool.js'
import { WSS_URL } from '@/constant/index.js'

export function initIM() {
	return new Promise(resolve => {
		const socket = uni.connectSocket({
			url: WSS_URL,
			fail: () => {}
		})
		uni.onSocketOpen(() => {
			console.log('连接已开启');
			resolve(socket)
		});
	})
}

export function openListener(callback) {
	uni.onSocketMessage(resp => {
		const { data } = resp
		try {
			const msg = JSON.parse(data)
			callback(msg)
		} catch {
			callback(data)
		}
	})
	uni.onSocketError(error => {
		console.log(error, 'error');
		toast({ title: "IM连接错误" })
	})
	uni.onSocketClose(() => {
		toast({ title: "IM退出" })
	})
}

export function checkIsToday(dateStr) {
	const date = new Date();
	const [year, month, day] = [date.getFullYear(), date.getMonth() + 1, date.getDate()]
	const str = `${year}-${patchZero(month)}-${patchZero(day)}`
	return dateStr === str
}

export function getHourStr(hour) {
	if (hour > 5 && hour <= 10) return '早上'
	if (hour > 10 && hour <= 12) return '中午'
	if (hour > 12 && hour <= 19) return '下午'
	if (hour > 19) return '晚上'

}

export function getLastTime(timestamp) {
	const date = new Date(timestamp * 1000);
	const [year, month, day, hour, minutes, ] = [date.getFullYear(), date.getMonth() + 1, date.getDate(), date
		.getHours(), date.getMinutes()
	]
	const dateStr = `${year}-${patchZero(month)}-${patchZero(day)}`
	const isToday = checkIsToday(dateStr)
	const endStr = `${patchZero(hour)}:${patchZero(minutes)}`
	if (!isToday) {
		return `${patchZero(month)}-${patchZero(day)} ${endStr}`
	}
	const hourStr = getHourStr(hour)
	return `${hourStr} ${patchZero(hour)}:${patchZero(minutes)}`
}

export function formatConversation(list, currentList) {
	if (!list || !Array.isArray(list) || !list.length) return []
	return list.filter(item => !!item.toUser).map(item => {
		const { nickname, avatar, id, sn } = item.toUser
		delete item.toUser
		const target = currentList.find(v => v.to_user_id * 1 === item.to_user_id * 1)
		return {
			...item,
			nickname,
			avatar,
			toUserId: id,
			toUserSn: sn,
			lastTime: getLastTime(item.last_send_time),
			page: target ? target.page : 1,
			hasInit: target ? target.hasInit : false,
			hasMore: target ? target.hasMore : false
		}
	})
}

export function formatUser(user, prefix) {
	const result = {}
	Object.keys(user).forEach(key => {
		result[`${prefix}_${key}`] = user[key]
	})
	return result
}

export function formatMessage(data, userId) {
	return data.map(item => {
		const { date_text, fromUser, content, from_user_id } = item
		const isSelf = from_user_id === userId
		const userData = formatUser(fromUser, 'msg')
		return { date_text, content, ...userData, self: isSelf }
	}).reverse()
}

const EVENT_STORE = {
	onMessage: null,
	onSystem: new Set(),
}

export function removeEventListener(name, cb) {
	if (!name || !cb) return
	if (!EVENT_STORE.hasOwnProperty(name)) return
	if (EVENT_STORE[name].has(cb)) {
		EVENT_STORE[name].delete(cb)
	}
}

export function addEventListener(eventName, callback) {
	if (!eventName || !callback) return
	if (!EVENT_STORE[eventName]) {
		EVENT_STORE[eventName] = new Set()
	}
	EVENT_STORE[eventName].add(callback)
}

export function addEvent(cb) {
	EVENT_STORE.onMessage = cb
}

export function triggerEvent(...payload) {
	if (!EVENT_STORE.onMessage) return
	EVENT_STORE.onMessage(...payload)
}